;+
; NAME:
;       DRIVER_IRDC
;
; PURPOSE:
;       Separately run the IRDC association algorithm and generate the
;       IDL save file './local/bgps_irdc.sav' for ease of other calculations.
;
; CATEGORY:
;       distance-omnibus IDL save file generator
;
; CALLING SEQUENCE:
;       driver_irdc
;
; INPUTS:
;       NONE
;
; OPTIONAL INPUTS:
;       NONE
;
; KEYWORD PARAMETERS:
;       NONE
;
; OUTPUTS:
;       './local/bgps_irdc.sav' containing the IDL structure BGPS_IRDC
;
; OPTIONAL OUTPUTS:
;       NONE
;
; COMMON BLOCKS:
;       IRDC_BLOCK    -- Constains the IRDC assocation structure data
;                        that is generated by driver_irdc.pro, plus
;                        the Peretto & Fuller (2009) IRDC catalog
;
; MODIFICATION HISTORY:
;
;       Created:  02/01/11, TPEB -- Formally writing this informal
;                                   driver as a standard routine in
;                                   the distance-omnibus repository.
;       Modified: 12/21/11, TPEB -- Name change to help clean up repository.
;
;-

PRO DRIVER_IRDC
  
  COMMON IRDC_BLOCK, pf_irdc, bgps_irdc
  
  ;; Restore the Peretto & Fuller (2009) IRDC catalog
  restore,'irdc_full_data.sav',/ver
  
  s = read_bgps_csv('bgps_distance_database.csv',csv,/ver)
  
  ;; Create the BGPS_IRDC structure
  bgps_irdc = REPLICATE( CREATE_STRUCT('cnum',0L,'amplitude',0.d,$
                                       'majax_ratio',0.,'pa_b',0.,$
                                       'b_maj',0.,'b_min',0.,$
                                       ;; IRDC Arrays of 20 elements
                                       'n_irdc',0,'hit_irdc',0,$
                                       'i_lcen',fltarr(20),'i_bcen',fltarr(20),$
                                       'i_maj',fltarr(20),'i_min',fltarr(20),$
                                       'pa_i',fltarr(20),'taup',fltarr(20),$
                                       'contrast',fltarr(20),'amp',fltarr(20),$
                                       'dist',fltarr(20)),$
                         csv.nrows)
  
  bgps_irdc.cnum = s.cnum
  
  ;; Get repository parameters
  defsysv, '!MW', exists = exists
  IF NOT exists THEN galactic_params 
  
  ;; Loop through all BGPS sources to calculate IRDC association probabilities
  FOR i=0L, csv.nrows-1 DO BEGIN
     
     pvec = prob_irdc(s[i], constrain=constraint)
     
     IF ((i+1) MOD 400) EQ 0 THEN print,'Working BGPS #'+$
                                        string(s[i].cnum,format="(I4)")
     
     ;; d = (dindgen(!MW.NBINS)*!MW.BINSIZE + !MW.BINSTART) / 1.d3
     ;; titlestr = string(s[i].cnum,s[i].glon_peak,s[i].glat_peak,format=$
     ;;                   "('BGPS #',I4,'  l = ',F5.1,'  b = ',F5.2)")
     ;; plot,d,pvec,yrange=[0,0.01],title=titlestr
     ;; wait,0.05
     
  ENDFOR

  ;; Save to disk
  save,bgps_irdc,filename='local/bgps_irdc.sav',/ver
  
END
